import {defineStore} from 'pinia'
import {useLoginApi, useLogoutApi} from '@/packages/admin/api/login.api'
import {useUserInfoApi} from '@/packages/admin/api/user'
import cache from '@/utils/cache'

export const userStore = defineStore('userStore', {
    state: () => ({
        user: {
            userId: '',
            userName: '',
            email: '',
            avatar: '',
            tenantId: ""
        },
        token: cache.getToken()
    }),
    actions: {
        setUser(val: any) {
            this.user = val;
        },
        setToken(val: any) {
            this.token = val
            cache.setToken(val)
        },
        removeToken() {
            cache.removeToken();
        },
        // 用户登录
        async loginAction(loginForm: any) {
            const res: any = await useLoginApi(loginForm)
            this.setToken(res.data.access_token)
            return res;
        },
        // 获取用户信息
        async getUserInfoAction() {
            const {data} = await useUserInfoApi(cache.getToken())
            this.setUser(data)
        },
        // 用户退出
        async logoutAction() {

            try {
                await useLogoutApi()
            } catch (e) {

            }

            this.setToken(null);
            // 移除 token
            this.removeToken();

        }
    }
})
